﻿using System;
using System.Security.Principal;
using System.Web;
using EPiServer.Personalization.VisitorGroups;
using Facebook.Web;
using SocialPack.Helpers;

namespace SocialPack.VisitorGroups.Facebook.Likes
{
    [VisitorGroupCriterion(
        Category = "Facebook",
        DisplayName = "Likes",
        Description = "Criterion that matches name of Facebook likes",
        LanguagePath = "/shell/cms/visitorgroups/criteria/likes")]
    public class LikesCriteria : CriterionBase<LikesModel>
    {
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public override bool IsMatch(IPrincipal principal, HttpContextBase httpContext)
        {
            try
            {
                FacebookWebContext context = new FacebookWebContext();

                if (context.AccessToken == null) // user has not allowed us to know his/hers likes
                    return false;

                int minNumberOfLikes = GetInteger(Model.MinimumLikes);

                return FacebookUtil.DoILikeIt(context.AccessToken, Model.Name, minNumberOfLikes);
            }
            catch (Exception ex)
            {
                _log.Error("CategoryCriteria IsMatch failed", ex);
                return false;
            }
        }

        private int GetInteger(MinimumLikes minimumLikes)
        {
            switch (minimumLikes)
            {
                case MinimumLikes.One:
                    return 1;
                case MinimumLikes.Two:
                    return 2;
                case MinimumLikes.Five:
                    return 5;
                case MinimumLikes.Ten:
                    return 10;
                default:
                    return 1;
            }
        }
    }
}